/**
 * Created by lijizhuang on 16/9/1.
 */
define(['jquery', 'underscore', 'backbone', 'common', 'url', 'text!modules/registerAndLogin/registerView.html', 'models/registerAndLogin/registerInfo', 'text!modules/registerAndLogin/registerFinishedView.html'],
    function ($, _, Backbone, Common, Url, registerViewTemplate, RegisterInfo, registerFinishedViewTemplate) {
        var registerView = Backbone.View.extend({
            template: _.template(registerViewTemplate),
            validateSuccess: true,

            initialize: function () {
                _registerView = this;
                timer = null;
                registerInfo = new RegisterInfo();
                this.model.bind('change:loggedIn', this.render, this);
            },

            events: {
                'submit .reg-content': 'onRegisterSubmit',
                'click input#get-captcha': 'onSendCaptcha'
            },

            onSendCaptcha: function (e) {
                e.preventDefault();
                $('#mobileErr').html('');

                var mobileReg = /^1[3|4|5|7|8]\d{9}$/;
                var value = $('#mobile').val();
                if ($.trim(value).length === 0) {
                    $('#mobileErr').html('*掌柜手机号不能为空');
                }
                else if (!mobileReg.test(value)) {
                    $('#mobileErr').html('*手机号格式不正确');
                }
                else {
                    //发送验证码请求,设置获取短信倒计时
                    Common.sendAjaxRequest(Url.mobileCaptcha, { "mobileNumber": value }, function (data) {
                        alert('验证码发送成功');
                    }, function (data) {
                        if (data.Content && data.Content.length > 0) {
                            alert(data.Content);
                            clearInterval(timer); //发送失败时，关闭timer
                            $('#get-captcha').show();
                            $('#reset-captcha').hide();
                        }
                    }, false);

                    var second = 60;
                    $('#get-captcha').hide();
                    $('#reset-captcha').val(second + '秒后重新获取');
                    $('#reset-captcha').show();

                    timer = setInterval(function () {
                        second -= 1;
                        if (second > 0) {
                            $('#reset-captcha').val(second + '秒后重新获取');
                        } else {
                            clearInterval(timer);
                            $('#get-captcha').show();
                            $('#reset-captcha').hide();
                        }
                    }, 1000);
                }
            },

            onRegisterSubmit: function (e) {
                e.preventDefault();
                $("input[type='submit']").attr('disabled', "true");
                $("input[type='submit']").val("提交注册中...");

                _registerView.clearErrorInfo();
                _registerView.validateSuccess = true;

                registerInfo.on('invalid', function (model, error) {
                    //注册表单验证结果处理
                    var errorArr = JSON.parse(error);
                    _.each(errorArr, function (err) {
                        _registerView.$el.find('#' + err.item).html('*' + err.error); //在表单后面添加异常信息
                    });

                    _registerView.validateSuccess = false;
                });

                registerInfo.set({
                    userName: $('#account').val(),
                    password: $('#password').val(),
                    email: $('#email').val(),
                    mobileNumber: $('#mobile').val(),
                    mobileCaptcha: $('#captcha').val(),
                    roleName: "BA",
                    ownerId: ""
                }, { 'validate': true });

                if (_registerView.validateSuccess) {
                    console.log('提交表单到服务端');
                    //在此判断表单是否提交成功
                    Common.sendAjaxRequest(Url.register, registerInfo.attributes, function (data) {
                        //提交成功后，载入成功页
                        _registerView.template = _.template(registerFinishedViewTemplate);
                        _registerView.render();
                    }, function (data) {
                        if (data.Content && data.Content.length > 0) {
                            alert(data.Content);
                            $("input[type='submit']").removeAttr("disabled");
                            $("input[type='submit']").val("提交信息");
                        }
                    }, false);
                }
            },

            clearErrorInfo: function () {
                $('#accountErr').html('');
                $('#passwordErr').html('');
                $('#emailErr').html('');
                $('#mobileErr').html('');
                $('#captchaErr').html('');
            },

            render: function () {
                //var tempValue = registerInfo.toJSON();
                $(this.el).empty().html(this.template(registerInfo.attributes));
                return this;
            }

        });

        return registerView;
    });